//
//  OrderViewController.m
//  WisdomZhuHai
//
//  Created by Admin on 14-10-30.
//  Copyright (c) 2014年 wyd. All rights reserved.
//

#import "OrderViewController.h"
#import "PayViewController.h"
#import "LoginViewController.h"
#import "TransforController.h"

@interface OrderViewController ()

@property (nonatomic,assign) BOOL ifLogined;
@property (nonatomic,assign) int priceCellIndex;
@property (nonatomic,assign) int allowanceIndex;
@property (nonatomic,assign) int phoneCellIndex;
@property (nonatomic,assign) int noteCellIndex;
@property (nonatomic,assign) int submitCellIndex;

//Cell都为唯一的，不做重用
@property (nonatomic,strong) UITableViewCell *priceCell;
@property (nonatomic,strong) UITableViewCell *allowanceCell;
@property (nonatomic,strong) UITableViewCell *phoneCell;
@property (nonatomic,strong) UITableViewCell *noteCell;
@property (nonatomic,strong) UITableViewCell *submitCell;

@property (nonatomic,strong) UITextField* txtPhone;
@property (nonatomic,strong) UITextField* txtCode;
@property (nonatomic,strong) UITextView* txtNote;
@property (nonatomic,strong) UITextField* txtAllowance;
@property (nonatomic,strong) UILabel* lbNum;
@property (nonatomic,strong) UILabel* lbPrice;
@property (nonatomic,strong) UIButton* btnAdd;
@property (nonatomic,strong) UIButton* btnReduce;
@property (nonatomic,strong) UIButton* btnSubmit;
@property (nonatomic,strong) UIButton* btnLogin;
@property (nonatomic,strong) UIButton* btnCheck;

@property (nonatomic,assign) CGFloat price;
@property (nonatomic,assign) int maxNum;
@property (nonatomic,assign) int minNum;
@property (nonatomic,assign) int curNum;
@property (nonatomic,strong) NSString* code;
@property (nonatomic,assign) float cash;
@property (nonatomic,strong) NSString* sn;

@end

@implementation OrderViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self checkLogin];
    
    self.priceCellIndex = 0;
    if (self.ifLogined) {
        self.phoneCellIndex = -1;
        self.allowanceIndex = -1;
        self.noteCellIndex = 1;
    }
    else {
        self.allowanceIndex = -1;
        self.phoneCellIndex = 1;
        self.noteCellIndex = 2;
    }
    self.submitCellIndex = self.noteCellIndex + 1;
    self.title = @"预订";
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapView:)];
    tapGesture.cancelsTouchesInView = NO;
    [self.tableView addGestureRecognizer:tapGesture];
    
    self.maxNum = 5;
    self.minNum = 1;
    self.curNum = self.minNum;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [Common colorWithRGB:0xf2f2f2];
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.tableView.bounds.size.width, 0.f)];
    self.tableView.tableFooterView.backgroundColor = self.tableView.backgroundColor;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self checkLogin];
    if (self.ifLogined) {
        self.phoneCell = nil;
        self.phoneCellIndex = -1;
        self.noteCellIndex = 1;
        self.submitCellIndex = 2;
    }
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)onAdd:(UIButton*)sender
{
    NSLog(@"onAdd");
    int num = self.lbNum.text.intValue;
    if (num >= self.maxNum) {
        return;
    }
    [self setGoodsNumber:++num];
    self.curNum = num;
    if (num >= self.maxNum) {
        [sender setEnabled:NO];
    }
    if (num > self.minNum) {
        [self.btnReduce setEnabled:YES];
    }
}

- (IBAction)onReduce:(UIButton*)sender
{
    NSLog(@"onReduce");
    int num = self.lbNum.text.intValue;
    if (num <= 1) {
        return;
    }
    [self setGoodsNumber:--num];
    self.curNum = num;
    if (num <= self.minNum) {
        [sender setEnabled:NO];
    }
    if (num < self.maxNum) {
        [self.btnAdd setEnabled:YES];
    }
}
//- (IBAction)onAllowanceCheck:(id)sender {
//    NSLog(@"onAllowanceCheck");
//    if (self.txtAllowance.text.length == 0) {
//        [[Common shareInstance] showAlertViewWithTitle:@"请输入代金券号码" text:nil dismissTime:1.0f];
//        return;
//    }
//    [self allowanceCheck];
//}

- (IBAction)onPhoneVarify:(id)sender
{
    NSLog(@"onPhoneVarify");
    if (self.txtPhone.text.length == 0 || ![Common regexWithType:e_phoneNumber string:self.txtPhone.text]) {
        [[Common shareInstance] showAlertViewWithTitle:@"请输入正确的手机号码" text:nil dismissTime:1.0f];
        return;
    }
    [self mobileValidation];
}

- (IBAction)onSubmit:(id)sender
{
    NSLog(@"onSubmit");
    if (![self checkCode]) {
        [[Common shareInstance] showAlertViewWithTitle:@"手机验证码不正确" text:nil dismissTime:1.0f];
        return;
    }
    [self submitOrder];
}

- (IBAction)onLogin:(id)sender
{
    NSLog(@"onLogin");
    LoginViewController *login = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
    login.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:login animated:YES];
}

- (void)onTapView:(UITapGestureRecognizer*)gesture
{
    NSLog(@"onTapView");
    [self.txtCode resignFirstResponder];
    [self.txtPhone resignFirstResponder];
    [self.txtNote resignFirstResponder];
//    [self.txtAllowance resignFirstResponder];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - Protocol request
//- (void)allowanceCheck
//{
//    [[ProtocolManager shareInstance] allowance:self.txtAllowance.text target:self selector:@selector(allowanceCheckCallback:)];
//}

- (void)mobileValidation
{
    [[ProtocolManager shareInstance] mobileValidation:self.txtPhone.text target:self selector:@selector(mobileValidationCallback:)];
}

- (void)submitOrder
{
//    int goodsId = [[Common valueForKey:P_ID dic:self.goodsInfo] intValue];
    int goodsId = [self.goodsId intValue];
    int num = self.lbNum.text.intValue;
    CGFloat totalPrice = num*self.price;
    NSString* note = self.txtNote.text;
    NSString* phone = self.txtPhone.text;
    NSString* couponCode = self.sn;
    [[ProtocolManager shareInstance] submitOrder:goodsId mobile:phone couponCode:couponCode num:num orderPrice:totalPrice orderSN:nil note:note target:self selector:@selector(submitOrderCallback:)];
}

#pragma mark - Protocol call back
- (void)allowanceCheckCallback:(NSDictionary*)dic
{
    NSLog(@"allowanceCheckCallback %@", dic);
    if (dic == nil) {
        return;
    }
    NSString *allowanceStatus = [Common valueForKey:P_STATUS dic:dic];
    if ([allowanceStatus isEqualToString:@"2"]) {
        [[Common shareInstance] showAlertViewWithTitle:@"该代金券已使用" text:nil dismissTime:1.0f];
        return;
    }
    else if ([allowanceStatus isEqualToString:@"3"]) {
        [[Common shareInstance] showAlertViewWithTitle:@"该代金券已过期" text:nil dismissTime:1.0f];
        return;
    }
    else if (allowanceStatus == nil) {
        [[Common shareInstance] showAlertViewWithTitle:@"没有该代金券" text:nil dismissTime:1.0f];
    }
    [[Common shareInstance] showAlertViewWithTitle:@"该代金券可以使用" text:nil dismissTime:1.0f];
    self.sn = [Common valueForKey:P_SN dic:dic];
    float cash = [[Common valueForKey:@"cash" dic:dic] floatValue];
    self.cash = cash;
    self.lbPrice.text = [NSString stringWithFormat:@"%.2f元(-%.2f元)", self.price, cash];
}

- (void)mobileValidationCallback:(NSDictionary*)dic
{
    NSLog(@"mobileValidationCallback %@", dic)
    if (dic == nil) {
        return;
    }
    self.code = [Common valueForKey:P_CODE dic:dic];
}

- (void)submitOrderCallback:(NSDictionary*)dic
{
    NSLog(@"submitOrderCallback %@", dic)
    if (dic == nil) {
        return;
    }
    NSString *respCode = [Common valueForKey:P_RESPCODE dic:dic];
    if (![respCode isEqualToString:CODE_HANDLE_SUCCESS]) {
        return;
    }
    NSString *sid = [Common valueForKey:P_SESSIONID dic:dic];
    NSString *loginName = [Common valueForKey:P_LOGINNAME dic:dic];
    if (self.txtPhone.text.length > 0) {
        [ProtocolManager shareInstance].sid = sid;
        [ProtocolManager shareInstance].loginName = loginName;
    }
    
    PayViewController *payViewCtrl = [[PayViewController alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height + 100) style:UITableViewStylePlain];
//    payViewCtrl.storeName = [Common valueForKey:P_NAME dic:self.storeInfo];
//    payViewCtrl.goodsName = [Common valueForKey:P_NAME dic:self.goodsInfo];
    payViewCtrl.goodsName = self.product_name;
    payViewCtrl.storeName = @"";
    payViewCtrl.num = self.lbNum.text.intValue;
    payViewCtrl.totalPrice = payViewCtrl.num*self.price - self.cash;
    payViewCtrl.orderInfo = dic;
    payViewCtrl.payment_mode = [NSString stringWithFormat:@"%@", _payment_mode];
    [self.navigationController pushViewController:payViewCtrl animated:YES];
    [TransforController umengEvent:@"OrderBuy" attributes:@{@"good_id" : self.goodsId, @"goods_name":self.product_name, @"amount":self.lbNum.text} number:@(self.price) ct:@"900007"];
}

#pragma mark - Private
- (void)setGoodsNumber:(int)num
{
    self.lbNum.text = [NSString stringWithFormat:@"%d", num];
    if (self.cash > 0.00001 ) {
        self.lbPrice.text = [NSString stringWithFormat:@"%.2f元(-%.2f元)", self.price*num,self.cash];
    }
    else{
        self.lbPrice.text = [NSString stringWithFormat:@"%.2f元", self.price*num];
    }
}

- (BOOL)checkCode
{
    if (self.ifLogined) {
        return YES;
    }
    if ([self.txtCode.text isEqualToString:self.code]) {
        return YES;
    }
    return NO;
    return YES;
}

- (void)checkLogin
{
    NSLog(@"%s || mobile:%@", __FUNCTION__, [ProtocolManager shareInstance].mobile);
    if ([ProtocolManager shareInstance].loginName.length > 0 && [ProtocolManager shareInstance].sid.length > 0 && [ProtocolManager shareInstance].mobile.length > 0) {
        self.ifLogined = YES;
    }
    else {
        self.ifLogined = NO;
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return self.submitCellIndex+1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == self.priceCellIndex) {
        return ORDER_PRICE_CELL_HEIGHT;
    }
    else if (indexPath.section == self.allowanceIndex)
    {
        return ORDER_ALLOWANCE_CELL_HEIGHT;
    }
    else if (indexPath.section == self.phoneCellIndex) {
        return ORDER_PHONE_CELL_HEIGHT;
    }
    else if (indexPath.section == self.noteCellIndex) {
        return ORDER_NOTE_CELL_HEIGHT;
    }
    else if (indexPath.section == self.submitCellIndex) {
        return ORDER_SUBMIT_CELL_HEIGHT;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == self.noteCellIndex) {
        return 26;
    }
    return 18.5;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* view = [[UIView alloc] init];
    view.backgroundColor = self.tableView.backgroundColor;
    if (section == self.noteCellIndex) {
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(12, 4, 100, 22)];
        lb.backgroundColor = [UIColor clearColor];
        lb.font = [UIFont systemFontOfSize:14];
        lb.text = @"备注";
        [view addSubview:lb];
    }
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = nil;
    if (indexPath.section == self.priceCellIndex) {
        if (self.priceCell == nil) {
            self.priceCell = [[NSBundle mainBundle] loadNibNamed:@"OrderCell"  owner:self options:nil][0];
            UIView* view = [_priceCell viewWithTag:1000];
            view.layer.cornerRadius = 3.0;
            view.layer.borderColor = [Common colorWithRGB:0xcccccc].CGColor;
            view.layer.borderWidth = 1;
//            view.layer.shadowOffset = CGSizeMake(1, 1);
//            view.layer.shadowOpacity = 0.2;
//            view.layer.shadowRadius = 1.0;
            UIButton *btnReduction = (UIButton*)[self.priceCell viewWithTag:1201];
            [btnReduction setImage:[UIImage imageNamed:@"Submit/Reduction.png"] forState:UIControlStateNormal];
            UIButton *btnAdd = (UIButton*)[self.priceCell viewWithTag:1203];
            [btnAdd setImage:[UIImage imageNamed:@"Submit/Add.png"] forState:UIControlStateNormal];
            
            self.lbNum = (UILabel*)[self.priceCell viewWithTag:1202];
            self.lbPrice = (UILabel*)[self.priceCell viewWithTag:1301];
            self.btnAdd = (UIButton*)[self.priceCell viewWithTag:1203];
            self.btnReduce = (UIButton*)[self.priceCell viewWithTag:1201];
        }
        UILabel *lbTitle = (UILabel*)[self.priceCell viewWithTag:1100];
//        NSString *storeName = [Common valueForKey:P_NAME dic:self.storeInfo];
//        NSString *goodsName = [Common valueForKey:P_NAME dic:self.goodsInfo];
//        lbTitle.text = [NSString stringWithFormat:@"%@ / %@", storeName, goodsName];
        lbTitle.text = self.product_name;
//        NSString *price = [Common valueForKey:P_PRICE dic:self.goodsInfo];
//        self.price = price.floatValue;
        self.price = self.product_price.floatValue;
        [self setGoodsNumber:self.curNum];
        
        cell = self.priceCell;
    }
    else if (indexPath.section == self.allowanceIndex) {
        if (self.allowanceCell == nil) {
            self.allowanceCell = [[NSBundle mainBundle] loadNibNamed:@"OrderCell"  owner:self options:nil][4];
            UIView *checkView = (UIView*)[self.allowanceCell viewWithTag:1303];
            UIButton *checkbtn = (UIButton*)[self.allowanceCell viewWithTag:1304];
            checkView.layer.cornerRadius = 3;
            checkbtn.layer.cornerRadius = 3;
            [checkbtn setBackgroundColor:[UIColor orangeColor]];
            self.btnCheck = checkbtn;
            self.txtAllowance = (UITextField*)[self.allowanceCell viewWithTag:1301];
        }
        cell = self.allowanceCell;
    }
    else if (indexPath.section == self.phoneCellIndex) {
        if (self.phoneCell == nil) {
            self.phoneCell = [[NSBundle mainBundle] loadNibNamed:@"OrderCell"  owner:self options:nil][1];
            UIView* view = [_phoneCell viewWithTag:1000];
            view.layer.cornerRadius = 3.0;
            view.layer.borderColor = [Common colorWithRGB:0xcccccc].CGColor;
            view.layer.borderWidth = 1;
//            view.layer.shadowOffset = CGSizeMake(1, 1);
//            view.layer.shadowOpacity = 0.2;
//            view.layer.shadowRadius = 1.0;
            UIButton *btn = (UIButton*)[self.phoneCell viewWithTag:1102];
            [btn setImage:[UIImage imageNamed:@"Submit/identifyingcode.png"] forState:UIControlStateNormal];
            [btn setImage:[UIImage imageNamed:@"Submit/identifyingcode2.png"] forState:UIControlStateHighlighted];
            
            self.txtPhone = (UITextField*)[self.phoneCell viewWithTag:1101];
            self.txtCode = (UITextField*)[self.phoneCell viewWithTag:1200];
        }
        cell = self.phoneCell;
    }
    else if (indexPath.section == self.noteCellIndex) {
        if (self.noteCell == nil) {
            self.noteCell = [[NSBundle mainBundle] loadNibNamed:@"OrderCell"  owner:self options:nil][2];
            self.txtNote = (UITextView*)[self.noteCell viewWithTag:1000];
            UIView* view = [_noteCell viewWithTag:1001];
            view.layer.cornerRadius = 3.0;
            view.layer.borderColor = [Common colorWithRGB:0xcccccc].CGColor;
            view.layer.borderWidth = 1;
//            view.layer.shadowOffset = CGSizeMake(1, 1);
//            view.layer.shadowOpacity = 0.2;
//            view.layer.shadowRadius = 1.0;
        }
        cell = self.noteCell;
    }
    else if (indexPath.section == self.submitCellIndex) {
        if (self.submitCell == nil) {
            self.submitCell = [[NSBundle mainBundle] loadNibNamed:@"OrderCell"  owner:self options:nil][3];
            
            self.btnSubmit = (UIButton*)[self.submitCell viewWithTag:1001];
            [self.btnSubmit setImage:[UIImage imageNamed:@"pay/submit_btn"] forState:UIControlStateNormal];
            [self.btnSubmit setImage:[UIImage imageNamed:@"pay/submit_btn_on"] forState:UIControlStateHighlighted];
        }
        self.btnLogin = (UIButton*)[self.submitCell viewWithTag:1002];
        if ([ProtocolManager shareInstance].loginName != nil) {
            self.btnLogin.hidden = YES;
            [self.btnSubmit setEnabled:YES];
        }
        else {
            [self.btnSubmit setEnabled:NO];
        }
        
        cell = self.submitCell;
    }

    cell.contentView.backgroundColor = self.tableView.backgroundColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"fuck");
    if ([textField isEqual:self.txtCode]) {

        if (self.code.length == 0) {
            [self.btnSubmit setEnabled:NO];
            return;
        }
        if ([textField.text isEqualToString:self.code]) {
            [self.btnSubmit setEnabled:YES];
        }
        else {
            [self.btnSubmit setEnabled:NO];
        }
    }
    if ([textField isEqual:self.txtAllowance]) {
        if (self.txtAllowance.text.length == 0) {
            [self.btnCheck setBackgroundColor:[UIColor grayColor]];
        }
        else {
            [self.btnCheck setBackgroundColor:[UIColor yellowColor]];
        }
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@""]) {
        return YES;
    }
    else if (range.location > 200) {
        return NO;
    }
    return YES;
}

@end
